package com.lwq.http.threads.users;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.http.impl.client.CloseableHttpClient;

import com.lwq.http.threads.utils.HttpThread;
import com.lwq.http.utils.model.HttpParamsMap;
import com.lwq.http.utils.model.HttpResult;


/**
* @author 作者 linweiqiang
* @version 创建时间：2017年10月19日 上午11:26:27
* 类说明
*/
public class UserThread implements Runnable{
	private CloseableHttpClient hc = null;
	private String uri = null;
	private Map<String,String> map = null;
	private int uNumber = 1;
	private int uThreads = 80;
	private long uTimeOut =  1000*60;
	private HttpParamsMap hpm = null;
	private long uSleepT = 0;
	private long sleepT = 0;
	private HttpResult hr = null;
	/**
	 * 请求线程
	 * @param hc CloseableHttpClient
	 * @param uri 请求地址
	 * @param map 请求参数
	 * @param uNumber 每个用户执行的次数
	 * @param nThreads 线程数（默认为80）
	 * @param timeOut 连接超时时间 （默认1分钟）
	 */
	public UserThread(CloseableHttpClient hc,String uri ,Map<String,String> map ,HttpParamsMap hpm , HttpResult hr ,long sleepT ,long usleepT) {
		this.hc = hc;
		this.uri = uri;
		this.map = map;
		this.hpm = hpm;
		this.hr = hr;
		this.uSleepT =usleepT;
		this.sleepT = sleepT;
	}
	/**
	 * 请求线程
	 * @param hc CloseableHttpClient
	 * @param uri 请求地址
	 * @param map 请求参数
	 * @param uNumber 每个用户执行的次数
	 * @param nThreads 线程数（默认为80）
	 * @param timeOut 连接超时时间 （默认1分钟）
	 */
	public UserThread(CloseableHttpClient hc,String uri ,Map<String,String> map,HttpParamsMap hpm ,HttpResult hr ,int uNumber ,int uThreads ,long uTimeOut ,long sleepT ,long usleepT) {
		this.hc = hc;
		this.uri = uri;
		this.map = map;
		this.hr = hr;
		this.uThreads = uThreads;
		this.uNumber = uNumber;
		this.uTimeOut = uTimeOut;
		this.hpm = hpm;
	}
	
	@Override
	public void run() {
		ExecutorService es = Executors.newFixedThreadPool(uThreads);
		System.out.println("user start");
		try {
			for (int i = 0; i < uNumber; i++) {
				es.submit(new HttpThread(hc,uri,map,hpm,hr,uSleepT));
				Thread.sleep(sleepT);
			}
			es.shutdown();
			if(!es.awaitTermination(uTimeOut, TimeUnit.MILLISECONDS)){
				es.shutdownNow();
			}
		} catch (Exception e) {
			System.out.println(e);
			es.shutdownNow();
		}
	}

}
